<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="分类名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入标签名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['articles:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['articles:category:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['articles:category:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column  align="center" label="图标">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.icon" />
          </template>
      </el-table-column>
      <el-table-column label="分类名" align="center" prop="name" />
      <el-table-column label="文章量" align="center" prop="articleCount" />
      <el-table-column label="点击量" align="center" prop="clickVolume" >
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.clickVolume }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort"  sortable>
        <template #default="scope">
          <el-tag type="warning">{{ scope.row.sort }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" >
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['articles:category:edit']">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)" v-hasPermi="['articles:category:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改博客标签对话框 -->
    <el-dialog :title="title" v-model="open" center>
      <el-form ref="tagRef" :model="form" :rules="rules">
          <el-form-item label="菜单图标" prop="icon"  label-width="120px">
            <el-popover
                placement="bottom-start"
                :width="540"
                v-model:visible="showChooseIcon"
                trigger="click"
                @show="showSelectIcon"
            >
              <template #reference>
                <el-input v-model="form.icon" placeholder="点击选择图标" @blur="showSelectIcon" v-click-outside="hideSelectIcon" readonly>
                  <template #prefix>
                    <svg-icon
                        v-if="form.icon"
                        :icon-class="form.icon"
                        class="el-input__icon"
                        style="height: 32px;width: 16px;"
                    />
                    <el-icon v-else style="height: 32px;width: 16px;"><search /></el-icon>
                  </template>
                </el-input>
              </template>
              <icon-select ref="iconSelectRef" @selected="selected" :active-icon="form.icon" />
            </el-popover>
          </el-form-item>
        <el-form-item label="分类名称" prop="name"  label-width="120px">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort"  label-width="120px">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitForm" style="margin-inline: 46%">确 定</el-button>
        <el-button @click="cancel" style="margin-inline: -45%">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script setup name="Category">
import {getCurrentInstance, reactive, toRefs} from "vue";
import {addCategory, delCategory, getCategory, listCategory, updateCategory} from "@/api/blog/category";
import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";

const { proxy } = getCurrentInstance();

const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const categoryList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    title: null,
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
    sort: [{ required: true, message: '必填字段', trigger: 'change' },
      { pattern: /^[0-9]\d*$/, message: '排序字段只能为自然数' },]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listCategory(queryParams.value).then(response => {
    categoryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    name: "",
    sort: ""
  };
  proxy.resetForm("tagRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value = selection.map(item => item.name);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分类";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getCategory(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分类";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["tagRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value
  const name = row.name || names.value
  proxy.$modal.confirm('是否确认删除类别名为"' + name + '"的数据项？').then(function() {
    return delCategory(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download("articles/category/export", {
    ...queryParams.value
  }, `category_${new Date().getTime()}.xlsx`);
}
/** 展示下拉图标 */
function showSelectIcon() {
  iconSelectRef.value.reset();
  showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
  form.value.icon = name;
  showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
  var elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;
  var className = elem.className;
  if (className !== "el-input__inner") {
    showChooseIcon.value = false;
  }
}
getList();
</script>
